package com.java.netty.common.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class VncEncoder extends MessageToByteEncoder {

   @Override
   protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf out) throws Exception {
      VncPacket vncPacket = (VncPacket) msg;
      ByteBuf header = null;
      ByteBuf body = null;
      try {
         header = PooledByteBufAllocator.DEFAULT.buffer();
         header = vncPacket.encode(header);

         body = PooledByteBufAllocator.DEFAULT.buffer();
         ByteBuf encode = vncPacket.getContent().encode(body);
         out.writeInt(4 + body.readableBytes() + 4);
         out.writeBytes(body);
         out.writeByte(header.readableBytes());
      } finally {
         header.release();
         body.release();
      }
   }
}
